<!--
 @description 创建商机
 @fileName Create.vue
 @author zengqiongying
 @created 2022/11/08 10:28:20
-->
<template>
  <div class="page-has-bottom bg_gray">
    <ComHeader :title="pageTitle" bg-color="#FAFBFE" />
    <div class="cus-fixed-bottom">
      <van-button type="primary" block round class="cus-btn-submit" :disabled="!enbleSubmit" @click="handlerConfirm">确定</van-button>
    </div>
    <van-form :show-error-message="false" @submit="handlerConfirm">
      <div class="category-title">品类选择</div>
      <div class="category-select">
        <LabelSelect
          v-model="formData.categorySelectionList"
          :url="`/data-dict/app/v2/dictionary/CRM_CATEGORY_SELECTION`"
          label-name="dictName"
          value-name="dictCode"
          method="get"
          :params=" { query: { appCode: 'top2-crm', domainCode: 'marketing' }, type: 0 }"
          multiple
          :includes="disConfCategorySelection"
        />
      </div>
      <FieldPicker
        v-if="showMeal && !!(disCode)"
        v-model="formData.setMealCode"
        :label.sync="formData.setMealName"
        title="套餐"
        placeholder="请选择"
        :url="`/app/v1/topSetMeal/${disCode}/page`"
        label-name="productName"
        value-name="productCode"
        method="post"
        :params=" { query: {enabled:1,dr:0}, type: 0 }"
        clear
      />
      <template v-if="hasCategory && showDesigner">
        <Cell
          title="设计师"
          :value="formData.recommendDesignerName"
          placeholder="请选择"
          @right="handleClickDesigner"
        />
        <FieldDateTime
          v-model="formData.expectMeasuredTime"
          title="量尺时间"
          placeholder="请选择"
          type="datetime"
          :default-date="formData.expectMeasuredTime"
          :min-date="measuredMinDate"
          clear
        />
      </template>
    </van-form>
  </div>
</template>

<script>
import Cell from '@/components/ListCell'
import FieldPicker from '@/components/FieldPicker'
import FieldDateTime from '@/components/FieldDateTime'
import LabelSelect from '@/components/LabelSelect'
import { bus } from '@/utils/bus'
import { createOpty, distributorConfigCategoryByDisCode } from '@/apis/customer'
export default {
  name: 'CustomerOptyCreate',
  components: { Cell, FieldPicker, FieldDateTime, LabelSelect },
  data() {
    return {
      shopDeptCode: this.$route.query.shopDeptCode || '',
      disCode: this.$route.query.disCode || '',
      clueCustomerId: this.$route.query.id || '',
      disConfCategorySelection: [], // 经销商类目
      formData: {
        // 商机
        categorySelectionList: [],
        recommendDesignerUserAccount: '',
        recommendDesignerName: '',
        recommendDesignerEmployeeId: '',
        recommendDesignerUserId: '',
        expectMeasuredTime: '',
        setMealCode: '',
        setMealName: ''
      },
      measuredMinDate: new Date()
    }
  },

  computed: {
    pageTitle() {
      return this.$route.name === 'CustomerTurnIntention' ? '转意向客户' : '创建商机'
    },
    isShopManager() {
      const t = this.$store.getters.userInfo
      return t.positionCodes && t.positionCodes.includes('top_shop_mg')
    },
    hasCategory() {
      return this.formData.categorySelectionList?.length > 0
    },
    showMeal() {
    // 是否显示套餐（品类选择成品且全屋定制时需选择套餐）
      const v = this.formData.categorySelectionList
      return v.includes('FinishedProductFurniture') && v.includes('WholeHouseCustom')
    },
    showDesigner() {
      // 品类只选择成品时不显示设计师选择
      const v = this.formData.categorySelectionList
      return !(v.length === 1 && v.includes('FinishedProductFurniture'))
    },
    // 是否包含定制
    containCustomize() {
      // const t = ['WholeHouseCustom', 'Bathroom', 'WTSCustomizedWardrobe', 'WTSCustomizedAmbry', 'WTSWallBoard', 'WTSWoodenDoors', 'WTSBathroom']
      return this.formData.categorySelectionList instanceof Array && !this.formData.categorySelectionList.every(e => e === 'FinishedProductFurniture')
    },
    enbleSubmit() {
      // return this.checkDataRequired()
      return this.formData.categorySelectionList.length > 0
    }
  },
  watch: {
    showMeal(v) {
      if (!v) {
        this.$set(this.formData, 'setMealCode', '')
        this.$set(this.formData, 'setMealName', '')
      }
    },
    showDesigner: {
      handler(v) {
        if (!v) {
          const t = 'recommendDesignerUserAccount recommendDesignerName recommendDesignerEmployeeId recommendDesignerUserId expectMeasuredTime'.split(' ')
          t.forEach(k => {
            this.$set(this.formData, k, '')
          })
        }
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    // 判断要去的页面不是/customer/selectDesigner页，就删除keepAlive的缓存状态
    if (to.path !== '/customer/selectDesigner') {
      this.$removeKeepAliveCache(this)
    }
    next()
  },

  async created() {
    this.disConfCategorySelection = await distributorConfigCategoryByDisCode(this.disCode)
  },
  activated() {
    this.updateDesigner()
  },

  mounted() {},

  methods: {
    // 选择设计师
    handleClickDesigner() {
      if (!this.shopDeptCode) {
        this.$toast('门店组织异常，无法操作')
        return
      }
      this.$router.push({ path: '/customer/selectDesigner', query: {
        orgCode: this.shopDeptCode
      }})
    },
    updateDesigner() {
      const str = localStorage.getItem('custom-add-designer')
      if (str) {
        try {
          const obj = JSON.parse(str)
          this.setDesignerData(obj)
        } catch (error) {
          this.setDesignerData('')
        }
        localStorage.removeItem('custom-add-designer')
      } else {
        // this.setDesignerData('')
      }
    },
    // 设置设计师数据
    setDesignerData(v) {
      this.$set(this.formData, 'recommendDesignerUserAccount', v ? v.account : '')
      this.$set(this.formData, 'recommendDesignerName', v ? v.name : '')
      this.$set(this.formData, 'recommendDesignerEmployeeId', v ? v.id : '')
      this.$set(this.formData, 'recommendDesignerUserId', v ? v.userId : '')
    },
    checkDataRequired(isShow) {
      const f = this.formData
      if (f.categorySelectionList.length === 0) {
        if (isShow) {
          this.$toast('请选择品类')
        }
        return false
      }
      /* if (this.showMeal && !f.setMealCode) {
        if (isShow) {
          this.$toast('请选择套餐')
        }
        return false
      } */
      if (this.showDesigner) {
        if (!f.recommendDesignerName) {
          if (isShow) {
            this.$toast('请选择设计师')
          }
          return false
        }
        if (!f.expectMeasuredTime) {
          if (isShow) {
            this.$toast('请选择量尺时间')
          }
          return false
        }
      }
      return true
    },
    handlerConfirm() {
      const flag = this.checkDataRequired(true)
      if (!flag) return
      const f = this.formData
      const data = {
        categorySelection: f.categorySelectionList.join(','),	// string品类选择 CRM_CATEGORY_SELECTION
        clueCustomerId: this.clueCustomerId,	// string线索客户id
        containCustomize: this.containCustomize,	// boolean
        expectMeasuredTime: f.expectMeasuredTime, //	string($date-time)预计量尺完成时间
        isShopOwnerCreate: this.isShopManager ? 1 : 0, //	integer($int32)是否店长创建:1=是，0=否
        recommendDesignerEmployeeId: f.recommendDesignerEmployeeId, //	string职员id
        recommendDesignerName: f.recommendDesignerName, //	string推荐设计师名
        recommendDesignerUserAccount: f.recommendDesignerUserAccount, //	string用户账号
        recommendDesignerUserId: f.recommendDesignerName,	// string用户id
        setMealCode: f.setMealCode, //	string套餐编码
        setMealName: f.setMealName //	string套餐名称
      }
      createOpty(data).then(res => {
        this.$toast('操作成功!')
        bus.$emit('refreshCustomerItem', {
          title: this.$route.name === 'CustomerTurnIntention' ? '转意向客户' : '创建商机',
          type: this.$route.name === 'CustomerTurnIntention' ? 'turnIntention' : 'createOpty',
          id: this.clueCustomerId
        })
        this.$router.go(-1)
      })
    }
  }
}

</script>
<style lang='less' scoped>
  .category-title{
    padding: 0 16px;
    height: 32px;
    line-height: 32px;
    font-size: 12px;
    color: #888A9C;
  }
  .category-select{
    padding: 16px 8px 0;
    background: #fff;
  }
</style>
